import React, { useEffect, useRef, useState } from 'react';
import NavBar from '@/components/NavBar';
import { Dialog, List, Toast } from 'antd-mobile';
import styles from './index.module.scss';
import { useDispatch } from 'react-redux';
import { getUserProfileAction, updateProfileAction } from '@/store/action/user';
import { useAppSelector } from '@/store';
import { Popup } from 'antd-mobile';
import { updatePhotoAction } from '@/store/action/user';
import { ProfileType } from '@/store/reducer/user';
import Input from '@/components/Input';
import TextArea from '@/components/TextArea';
import { DatePicker } from 'antd-mobile';
import dayjs from 'dayjs';
import { clearToken } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

type EditType = 'photo' | 'gender' | 'name' | 'intro';
export default function ProfileEdit() {
  const history = useHistory();
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getUserProfileAction());
  }, [dispatch]);

  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);
  const [editType, setEditType] = useState('' as EditType);

  const { profile } = useAppSelector((state) => state.user);
  const [name, setName] = useState('');

  const [intro, setIntro] = useState('');

  useEffect(() => {
    setName(profile.name || '');
  }, [profile.name]);

  useEffect(() => {
    setIntro(profile.intro || '');
  }, [profile.intro]);

  const uploadRef = useRef<HTMLInputElement>(null);
  const handleUploadClick = () => uploadRef.current?.click();

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      await dispatch(updatePhotoAction(formData));
      Toast.show({ content: '更新成功' });
      setVisible(false);
    }
  };
  const handleShowEdit = (editType: EditType) => {
    setEditType(editType);
    if (editType === 'photo' || editType === 'gender') {
      setVisible(true);
    }

    if (editType === 'name' || editType === 'intro') {
      setRightVisible(true);
    }
  };

  const handleUpdateProfile = async (data: Partial<ProfileType>) => {
    await dispatch(updateProfileAction(data));
    Toast.show({ content: '更新成功' });
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
  };

  const handleBack = () => {
    setRightVisible(false);
    editType === 'name' && setName(profile.name);
    editType === 'intro' && setIntro(profile.intro);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    if (e.key === 'Enter') {
      editType === 'name' && handleUpdateProfile({ name });
      editType === 'intro' && handleUpdateProfile({ intro });
    }
  };

  const handleLogOut = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定退出吗？',
      onConfirm: () => {
        clearToken();
        history.push('/login');
        Toast.show({ content: '退出成功' });
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handleShowEdit('photo')}
            >
              头像
            </List.Item>

            <List.Item arrow extra={profile.name} onClick={() => handleShowEdit('name')}>
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => handleShowEdit('intro')}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => handleShowEdit('gender')}
            >
              性别
            </List.Item>
            <List.Item arrow extra={profile.birthday} onClick={() => setBirthVisible(true)}>
              生日
            </List.Item>
          </List>
          <input
            ref={uploadRef}
            className="avatar-upload"
            type="file"
            onChange={(e) => handleFileChange(e)}
          />
        </div>

        <div className="logout">
          <button className="btn" onClick={handleLogOut}>
            退出登录
          </button>
        </div>
        <Popup
          visible={visible}
          position="bottom"
          bodyClassName="popup-bottom-list"
          onMaskClick={() => setVisible(false)}
        >
          {editType === 'photo' && (
            <>
              <div className="list-item" onClick={handleUploadClick}>
                拍照
              </div>
              <div className="list-item" onClick={handleUploadClick}>
                本地选择
              </div>
              <div className="list-item" onClick={() => setVisible(false)}>
                取消
              </div>
            </>
          )}
          {editType === 'gender' && (
            <>
              <div className="list-item" onClick={() => handleUpdateProfile({ gender: 0 })}>
                男
              </div>
              <div className="list-item" onClick={() => handleUpdateProfile({ gender: 1 })}>
                女
              </div>
              <div className="list-item" onClick={() => setVisible(false)}>
                取消
              </div>
            </>
          )}
        </Popup>
        <Popup visible={rightVisible} position="right" bodyClassName="popup-right" destroyOnClose>
          {(editType === 'name' || editType === 'intro') && (
            <>
              <NavBar
                onBack={handleBack}
                right={
                  <span
                    className="submit-btn"
                    onClick={() =>
                      handleUpdateProfile({ [editType]: editType === 'name' ? name : intro })
                    }
                  >
                    提交
                  </span>
                }
              >
                编辑{editType === 'name' ? '昵称' : '简介'}
              </NavBar>
              <div className="edit-content">
                {editType === 'name' ? (
                  <Input
                    className="edit-input"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    autoFocus
                    onKeyDown={(e) => handleKeyDown(e)}
                  />
                ) : (
                  <TextArea
                    onKeyDown={(e) => handleKeyDown(e)}
                    value={intro}
                    onChange={(e) => setIntro(e.target.value)}
                  ></TextArea>
                )}
              </div>
            </>
          )}
        </Popup>
        <DatePicker
          title="选择生日"
          visible={birthVisible}
          max={new Date()}
          min={new Date('1900-01-01')}
          defaultValue={new Date()}
          value={new Date(profile.birthday)}
          onConfirm={(val) => handleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') })}
          onClose={() => setBirthVisible(false)}
        ></DatePicker>
      </div>
    </div>
  );
}
